<template>
    <div class="container">
        <m-header>购票详情</m-header>
        <div class="main">
            <div class="info-wrap" v-for="(ite,ind) in groupList" :key="ind">
                <div class="title">{{ite.title}}</div>
                <div class="content">
                    <template v-for="(item,index) in ite.field">
                        <div class="cell" :key="index" v-if="isShowField(item.label)">
                            <m-form
                                    :field="item"
                                    :value="value[item.field_id]"
                                    :disabled="item.disabled"
                                    @change="onChange"
                            >

                                <template #value>
                                    <!--订单编号后显示订单二维码-->
                                    <template v-if="item.field_id === 'out_trade_no'">
                                        <van-icon name="qr" size="24" class="qr" color="#24C373" @click.stop="generateQRCode" />
                                    </template>

                                    <!--订单状态-->
                                    <template v-if="item.field_id === 'Order_status'">
                                        <div :class="statusClass" class="status">{{statusName}}</div>
                                    </template>

                                </template>
                            </m-form>

                            <!--蒙层，阻止修改，点击提示信息-->
                            <div v-if="item.showMask" class="mask" @click="beforeChange"></div>
                        </div>
                    </template>

                    <div class="cell" v-if="!ind">
                        <div class="label">照片样本</div>
                        <div class="value" @click="previewQr"><img ref="demoImg" src="@/assets/images/pic_demo.jpg" alt=""></div>
                    </div>
                </div>
            </div>

        </div>
        <div class="footer">
            <div style="display: flex;justify-content: space-around;">
            <van-button class="btn" color="#24C373" plain @click="cancelOrder" v-if="value.Order_status === '待支付'" v-prevent-re-click>取消订单</van-button>
            <van-button class="btn" color="#24C373" @click="onPay" v-if="value.Order_status === '待支付'" v-prevent-re-click>立即支付</van-button>
            <van-button class="btn" color="#24C373" plain @click="showRefund = true" v-if="isRefund" v-prevent-re-click>申请退票</van-button>
            <van-button class="btn" color="#24C373" @click="cancelRefund" v-if="value.Order_status === '申请退款中'" v-prevent-re-click>取消退票</van-button>
            <!--<van-button class="btn" color="#24C373" @click="onInvoice" v-if="value.Order_status === '已支付'" v-prevent-re-click>申请开票</van-button>-->
            </div>
        </div>
        <!--支付前购票协议弹出层-->
        <m-agreement v-model="showAgreement" @agree="onAgree" :closeSign="true"></m-agreement>

        <!--订单二维码弹窗-->
        <van-popup v-model="showQrcode" closeable :round="true"  duration="0.2" max-height="80vh">
            <div class="popup-wrap">
                <div class="title">订单二维码</div>
                <div class="content">
                    <div class="qrcode" ref="qrcode" v-if="">

                    </div>
                    <div class="pic" v-if="statusName === '已过期'">
                        <img src="@/assets/images/order/pic_none_guoqi.png" alt="">
                    </div>
                    <div class="pic" v-else-if="statusName === '待支付'">
                        <img src="@/assets/images/order/pic_none_daizhifu.png" alt="">
                    </div>
                    <div class="pic" v-else-if="statusName === '已退票'">
                        <img src="@/assets/images/order/pic_none_tuipiao.png" alt="">
                    </div>
                    <div class="pic" v-else-if="statusName === '申请退票中'">
                        <img src="@/assets/images/order/pic_none_tuipiaozhong.png" alt="">
                    </div>
                    <div class="pic" v-else-if="statusName === '购票失败'">
                        <img src="@/assets/images/order/pic_none_shibai.png" alt="">
                    </div>
                    <div class="fx" v-for="(ite,index) in qrField">
                        <template  v-for="item in ite">
                            <div class="cell" v-if="isShowField(item.label)">
                                <div class="label">{{item.label}}：</div>
                                <div class="value">{{value[item.field_id]}}</div>
                            </div>
                        </template>

                    </div>
                </div>
            </div>
        </van-popup>

        <van-popup v-model="showRefund" closeable :round="true"  duration="0.2">
            <div class="popup-wrap">
                <div class="title">申请退票</div>
                <div class="content">
                    <!--<textarea class="textarea" v-model="refundCause" placeholder="请输入退票原因"></textarea>-->
                    <van-form class="form" ref="formRef">
                    <van-field
                            v-model="refundCause"
                            :label-width="0"
                            name="refundCause"
                            placeholder="退票原因"
                            type="textarea"
                            :rules="[{ required: true, message: '请填写退票原因' }]"
                    />
                    </van-form>
                </div>
                <div class="btn-wrap">
                    <van-button class="btn" @click="showRefund = false" v-prevent-re-click>取消</van-button>
                    <van-button class="btn" color="#24C373" @click="onRefund" v-prevent-re-click>确定</van-button>
                </div>
            </div>
        </van-popup>

    </div>
</template>

<script>
  import form from '@/components/form/form'
  import agreement from '@/components/agreement/agreement'
  import dialog from '@/utils/dialog'
  import {getOrder,editOrder,unifiedorder,applyRefund, getParameter,unLockTicket} from "../../request/api";
  import {crtTimeFtt} from "../../utils/utils";
  import {preventReClick} from "../../utils/plugins";
  import {setToken} from "../../utils/cache";
  import {Popup,ImagePreview,Field,Form } from 'vant'
  import QRCode from 'qrcodejs2'

  export default {
    name: "cticketDetail",
    components: {
      "m-form": form,
      "m-agreement": agreement,
      [Popup.name]: Popup,
      [ImagePreview.Component.name]: ImagePreview.Component,
      [Field.name]: Field,
      [Form.name]: Form,
    },
    computed: {
      isRefund(){
        let {Order_status, effective_time_end,Order_refund_time} = this.value;
        let nowTime = new Date().getTime(),
          endTime = effective_time_end && new Date(crtTimeFtt(effective_time_end,'YYYY/MM/DD HH:mm:ss')).getTime();
        endTime = Math.abs(endTime) + (this.refundDays * 24 * 60 * 60 * 1000)
        return Order_status === '已支付' && endTime > nowTime && !Order_refund_time
      },

      statusClass(){
        let {statusName} = this;
        return statusName === '待支付' ? 'blue'
          : statusName === '待使用' ? 'green'
            : statusName === '使用中' ? 'green'
              :statusName === '申请退票中' ? 'orange'
                : statusName === '已退票' ? 'red'
                  : statusName === '已过期' ? 'yellow'
                    : statusName === '购票失败' ? 'red'
                      : 'grey'
      },
      statusName(){
        let {Order_status,effective_time_start,effective_time_end} = this.value,
          name = Order_status,
          now = new Date().getTime(),
          start = new Date(effective_time_start).getTime(),
          end = new Date(effective_time_end).getTime();
        if (Order_status === '已支付' && now < start) name = '待使用';
        if (Order_status === '已支付' && now < end) name = '已过期';
        if (Order_status === '已支付' && start < now < end) name = '使用中'
        console.log(name);
        return name;
      },

      isShowField(){
        return function(label){
          let {packag_type_id} = this.value;
          if (['去程上车点','去程到达点','去程出发时间'].includes(label) ){
            return (packag_type_id === 'tplx001' || packag_type_id === 'tplx003')
          }
          if (['回程上车点','回程到达点','回程出发时间'].includes(label)){
            return (packag_type_id === 'tplx002' || packag_type_id === 'tplx003')
          }
          return true
        }

      }
    },
    watch:{
      ['$route']: {
        handler(val){
          if (val.path === '/cticketDetail'){
            let query = val.query,
              {token,id,shuttle} = query;
            //微信信息通知推送，带有token的，保存token后重载，清除带有token的地址参数
            if (token){
              setToken(token);
              let dir = process.env.NODE_ENV === 'development' ? process.env.VUE_APP_SECONDDIR : window.webConfig.webSecondDir
              location.replace(`${dir}cticketDetail?id=${id || ''}&shuttle=${shuttle || ''}`);
              return
            }
            if (id) {
              this.getOrder({out_trade_no:id,shuttle_type: '定制'});
              return
            }
            if (shuttle){
              this.getOrder({shuttle_id:shuttle,no: 1,size: 1,shuttle_type: '定制'});
            }
          }
        },immediate: true
      }
    },

    data() {
      return {
        groupList: [
          {
            title:  '订单信息',
            field:[
              {
                label: '订单编号',
                type: 'text',
                field_id: 'out_trade_no',
                disabled: true
              },
              {
                label: '群二维码',
                type: 'picture',
                field_id: 'group_qrcode',
                picLimit: 1,
                disabled: true,
              },
              {
                label: '状态',
                type: 'text',
                field_id: 'Order_status',
                disabled: true,
                valueSlot: true
              },
              {
                label: '套票类型',
                type: 'text',
                field_id: 'packag_type_name',
                disabled: true
              },
              {
                label: '座位号',
                type: 'text',
                field_id: 'seat_no',
                disabled: true
              },
              {
                label: '姓名',
                type: 'text',
                field_id: 'passengers_name',
                disabled: true
              },
              {
                label: '证件类型',
                type: 'text',
                field_id: 'identification_type_name',
                disabled: true

              },
              {
                label: '证件号',
                type: 'text',
                field_id: 'identification_no',
                disabled: true
              },
              {
                label: '讫地',
                type: 'text',
                field_id: 'school_name',
                disabled: true
              },
              /*{
                label: '票种',
                type: 'text',
                field_id: 'ticket_typall_name',
                disabled: true
              },
              {
                label: '购票金额',
                type: 'text',
                field_id: 'Order_amount',
                disabled: true
              },
              {
                label: '已支付购票金额',
                type: 'text',
                field_id: 'payer_total',
                disabled: true
              },*/
              {
                label: '订单创建时间',
                type: 'text',
                field_id: 'input_time',
                disabled: true
              },
              {
                label: '申请退票原因',
                type: 'text',
                field_id: 'Order_refund_reason',
                disabled: true
              },
              {
                label: '签名照片',
                type: 'picture',
                field_id: 'agreement_handwritten_pic',
                picLimit: 1,
                disabled: true,
              },
              {
                label: '协议照片',
                type: 'picture',
                field_id: 'agreement_all_pic',
                picLimit: 1,
                disabled: true,
              },
              {
                label: '乘车人照片',
                message: '近期清晣正面头部照片',
                type: 'picture',
                field_id: 'pictures_link',
                picLimit: 1,
                disabled: false,
                showMask: false
              },

            ]
          },
          {
            title:  '套票信息',
            field:[
              {
                label: '班车座位表名称',
                type: 'text',
                field_id: 'shuttle_seat_name',
                disabled: true
              },
              {
                label: '套票名称',
                type: 'text',
                field_id: 'shuttle_name',
                disabled: true
              },
              {
                label: '套票类型',
                type: 'text',
                field_id: 'packag_type_name',
                disabled: true
              },
              {
                label: '班车类型',
                type: 'text',
                field_id: 'shuttle_type',
                disabled: true
              },
              {
                label: '去程上车点',
                type: 'text',
                field_id: 'up_stop_name',
                disabled: true
              },
              {
                label: '去程到达点',
                type: 'text',
                field_id: 'school_name',
                disabled: true
              },
              {
                label: '去程出发时间',
                type: 'text',
                field_id: 'up_departure_time',
                disabled: true
              },
              {
                label: '回程上车点',
                type: 'text',
                field_id: 'school_name',
                disabled: true
              },
              {
                label: '回程到达点',
                type: 'text',
                field_id: 'down_stop_name',
                disabled: true
              },
              {
                label: '回程出发时间',
                type: 'text',
                field_id: 'down_departure_time',
                disabled: true
              },
              {
                label: '套票说明',
                type: 'text',
                field_id: 'mark',
                disabled: true
              },
              {
                label: '票种',
                type: 'text',
                field_id: 'ticket_typall_name',
                disabled: true
              },
              {
                label: '票价',
                type: 'text',
                field_id: 'Order_amount',
                disabled: true,
              },
              {
                label: '已支付购票金额',
                type: 'text',
                field_id: 'payer_total',
                disabled: true
              },
              {
                label: '车票有效时间起',
                type: 'text',
                field_id: 'effective_time_start',
                disabled: true,
              },
              {
                label: '车票有效时间止',
                type: 'text',
                field_id: 'effective_time_end',
                disabled: true,
              },

            ]
          },
        ],
        value: {},
        disabled: true,

        showAgreement: false,

        status: '4', //1、待支付 2、待使用 3、使用中   4、申请退票中  5、已退票  6、失败 7、已使用

        //显示订单二维码
        showQrcode: false,
        qrcode: null,
        qrField:[
          [{
            label: '去程上车点',
            type: 'text',
            field_id: 'up_stop_name',
          },],
          [{
            label: '去程到达点',
            type: 'text',
            field_id: 'school_name',
          },],
          [{
            label: '去程出发时间',
            type: 'text',
            field_id: 'up_departure_time',
          },],
          [{
            label: '回程上车点',
            type: 'text',
            field_id: 'school_name',
          },],
          [{
            label: '回程到达点',
            type: 'text',
            field_id: 'down_stop_name',
          },],
          [{
            label: '回程出发时间',
            type: 'text',
            field_id: 'down_departure_time',
          },],

          [{
            label: '班车名称',
            type: 'text',
            field_id: 'shuttle_name',
          },],
          [{
            label: '班车座位表名称',
            type: 'text',
            field_id: 'shuttle_seat_name',
          },],
          [{
            label: '座位号',
            type: 'text',
            field_id: 'seat_no',
          },],
          [{
            label: '票类',
            type: 'text',
            field_id: 'ticket_typall_name',
          },],
          [{
            label: '乘车人',
            type: 'text',
            field_id: 'passengers_name',
          },],
          [{
            label: '身份证',
            type: 'text',
            field_id: 'identification_no',
          },],
          [{
            label: '订单号',
            type: 'text',
            field_id: 'out_trade_no',
          },],
          [{
            label: '有效期起',
            type: 'text',
            field_id: 'effective_time_start',
          }],
          [{
            label: '有效期止',
            type: 'text',
            field_id: 'effective_time_end',
          }],
        ],

      //  申请退票弹出层
        showRefund: false,
      //  退票原因
        refundCause: '',

      //  过期天数可申请退票
        refundDays: 0
      }
    },
    methods: {
      //申请退票
      onRefund(){
        this.$refs.formRef.validate('refundCause').then(() => {
          let {out_trade_no} = this.value;
          this.applyRefund_(out_trade_no,true,this.refundCause).then(() => this.showRefund = false);
        })
        /*dialog.confirm('确认申请退票吗？','退票成功后不能再使用','确定申请').then(() =>{
          let {out_trade_no} = this.value;
          this.applyRefund_(out_trade_no,true);
          console.log('确定申请');
        },()=>{})*/
      },
      cancelRefund(){
        // this.$Toast('功能正在开发中');
        // return;
        dialog.confirm('确认取消申请退票吗？').then(() =>{
          let {out_trade_no} = this.value;
          this.applyRefund_(out_trade_no,false);
          console.log('确定取消');
        },()=>{})

      },
      applyRefund_(id,isRefund,resson){
        return new Promise(resolve => {
          this.$Loading();
          applyRefund(id,isRefund,resson).then(res => {
            if (res.errcode !== 0)return;
            this.getOrder({out_trade_no: id});
            resolve();
          })
        })
      },
      onPay(){
        // this.$Toast('功能正在开发中');
        // return;
        this.showAgreement = true;
      },
      onAgree(val){
        this.$Loading();
        this.weUnifiedorder(this.value.out_trade_no)
      },
      //取消订单
      cancelOrder(){
        dialog.confirm('确认取消订单吗？','取消后可重新下单','确定取消').then(() =>{
          let {out_trade_no} = this.value;
          unLockTicket(out_trade_no,'用户取消订单').then(res => {
            if (res.errcode !== 0) return;
            this.getOrder({out_trade_no});
          })
        },()=>{})
      },
      getOrder(param){
        this.$Loading();
        //{out_trade_no: id}
        getOrder(param).then(res => {
          if (res.errcode !== 0)return;
          this.$toast.clear();
          let data = res.row[0];
          let {Order_create_time,Order_status,effective_time_start,effective_time_end} = data;
          let nowTime = new Date().getTime(),
            endTime = Order_create_time && new Date(crtTimeFtt(Order_create_time,'YYYY/MM/DD HH:mm:ss')).getTime();
          // effective_time_start && (data.effective_time_start = crtTimeFtt(effective_time_start,'YYYY-MM-DD'));
          // effective_time_end && (data.effective_time_end = crtTimeFtt(effective_time_end,'YYYY-MM-DD'));
          this.value = data;
          this.groupList[0].field[9].showMask = nowTime < (endTime + 60 *60 *1000) || Order_status !== '已支付'

        })
      },
      beforeChange(){
        this.$Toast('售出1小时后才可修改')
      },
      onChange(e){
        let {field,val} = e,
          {field_id} = field;
        if (field_id === 'pictures_link') {
          console.log(val);
          let {out_trade_no} = this.value;
          let param = {pictures_link: val,out_trade_no}
          this.$Loading();
          editOrder(param).then(res => {
            if (res.errcode !== 0)return;
            this.$Toast('修改成功')
          })
        }
      },

      //  微信统单
      weUnifiedorder(id){
        return new Promise(resolve => {
          unifiedorder(id).then(res => {
            if (res.errcode !== 0)return;
            let data = res.row && res.row[0]
            this.$toast.clear();
            const onBridgeReady = () => {
              WeixinJSBridge.invoke(
                'getBrandWCPayRequest', {
                  "appId": data.appId,     //公众号名称，由商户传入
                  "timeStamp": data.timeStamp,         //时间戳，自1970年以来的秒数
                  "nonceStr": data.nonceStr, //随机串
                  "package": data.package,
                  "signType": data.signType,         //微信签名方式：
                  "paySign": data.paySign //微信签名
                },
                (res) => {
                  if (res.err_msg == "get_brand_wcpay_request:ok") {
                    // 使用以上方式判断前端返回,微信团队郑重提示：
                    //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                    this.$Toast('支付成功',() => {
                      // this.$router.push({path: '/ticketDetail',query: {id}})
                      this.getOrder({out_trade_no:id});
                    })
                  }
                  else {
                    //  支付失败
                    this.$Toast('支付失败')
                  }
                });

            }

            if (typeof WeixinJSBridge == "undefined") {
              if (document.addEventListener) {
                document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
              } else if (document.attachEvent) {
                document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
              }
            } else {
              onBridgeReady();
            }
          })
        })
      },

      // 申请开票
      onInvoice(){
        let {out_trade_no,effective_time_end} = this.value;
        let nowTime = new Date().getTime(),
          endTime = effective_time_end && new Date(crtTimeFtt(effective_time_end,'YYYY/MM/DD HH:mm:ss')).getTime();
        if (nowTime > endTime){
          this.$Loading();
          getParameter({id: 'invoice_url'}).then(res =>{
            if (res.errcode !== 0)return;
            this.$toast.clear();
            let data = res.row[0],
              url =  data.parameter_unit;
            location.href = url + out_trade_no;
          })
        }else {
          this.$Toast('车票有效时间未结束，不能开票')
        }
      },
      // 获取开票地址参数
      getInvoiceUrl(){

      },
      //生成订单二维码
      generateQRCode() {
        this.showQrcode = true;
        this.$nextTick(() =>{
          if (this.qrcode!= null) {
            this.$refs.qrcode.innerHTML = ''
          }
          if (this.value.Order_status === '已支付'){
            this.qrcode = new QRCode(this.$refs.qrcode, {
              width: 180,
              height: 180,
              text: this.value.out_trade_no
            })
          }
        })
      },

      //  预览图片
      previewQr(url){
        ImagePreview({
          images: [this.$refs.demoImg[0].src],
          showIndex: false,
          overlayStyle: {
            "background": "rgba(0,0,0,0.5)"
          }
        });
      },

      // 获取退票参数
      getRefundParameter(){

      },
    },
    mounted(){
      getParameter({id: 'cs003'}).then(res =>{
        if (res.errcode !== 0)return;
        this.$toast.clear();
        let data = res.row[0],
          val =  data.parameter_value;
        this.refundDays = val || 0;
      })
    }
  }
</script>

<style scoped lang="less">

    .main{
        padding: 10px;
        overflow: auto;
        .info-wrap{
            margin-bottom: 10px;
            .cell{
                position: relative;
                display: flex;
                align-items: center;
                .label{
                    font-size: 15px;
                    color: #999;
                }
                .value{
                    flex: 1;
                    width: 0;
                    & > img{
                        width: 100%;
                    }
                }
                .mask{
                    position: absolute;
                    width: 100%;
                    height: 100%;
                    z-index: 100;
                    top: 0;
                    left: 0;
                }
                .status{
                    text-align: right;
                    font-size: 15px;
                    width: 100%;
                }
                .blue{
                    color: #1989fa;
                }
                .green{
                    color: #24C373;
                }
                .red{
                    color: #FF1313;
                }
                .yellow{
                    color: #ffd11b;
                }
                .orange{
                    color: #FF7913;
                }
                .grey{
                    color: #B3B3B3;
                }
            }

        }
    }
    .footer{
        padding: 10px;
        .btn{
            width: 100%;
            & +.btn{
                margin-left: 10px;

            }
        }
    }

    .popup-wrap{
        width: 80vw;
        max-height: 90vh;
        display: flex;
        flex-direction: column;
        align-items: center;
        /*height: 571px;*/

        .title{
            padding: 15px 15px 10px;
            color: #333333;
            font-size: 17px;
            font-weight: bold;
        }
        .content{
            flex: 1;
            height: 0;
            overflow: auto;
            padding: 0 15px 15px;
            color: #333333;
            font-size: 15px;
            width: 100%;
            display: flex;
            flex-direction: column;
            box-sizing: border-box;
            align-items: center;

            p{
                margin: 0;
            }
            .bold{
                font-weight: bold;
            }
            .pic{
                width: 85%;
                & >img{
                    width: 100%;
                }
            }
            .qrcode{
                width: fit-content;
            }
            .fx{
                display: flex;
                width: 100%;
            }
            .cell{
                padding-top: 10px;
                width: 100%;
                display: flex;
                .label{
                }
                .value{
                    flex: 1;
                }
            }

            .form{
                width: 100%;
                border:1px solid #e6e6e6;
                box-sizing: border-box;
                min-height: 100px;
            }
            .textarea{
                outline: none;
                width: 100%;
                border: 1px solid #e6e6e6;
                padding: 10px;
            }
        }
        .btn-wrap{
            width: 100%;
            padding: 5px 15px 15px;
            box-sizing: border-box;
            display: flex;
            .btn{
                width: 100%;
                & + .btn{
                    margin-left: 16px;
                }
            }
        }
    }

</style>
